using AutoMapper;
using B.S.BaseData.Domain;
using MediatR;
using SmartTracking.API.Read.Application.Commands.ZXL.Procurementr;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace SmartTracking.API.Read.Application.CommandHandlers.ZXL.Procurementr
{
    public class GetProcurementCommandHandler : IRequestHandler<GetProcurementCommand, ApiPaging<Procurement>>
    {

        private readonly IBaseRepository<Procurement> procurement;
        private readonly IMapper map;

        public GetProcurementCommandHandler(IBaseRepository<Procurement> procurement, IMapper map)
        {
            this.procurement = procurement;
            this.map = map;
        }

        public Task<ApiPaging<Procurement>> Handle(GetProcurementCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<Procurement> page = new ApiPaging<Procurement>();

            var linq = procurement.GetAll().Where(x=>x.IsDeleted == false);

            page.totalCount = linq.Count();
            page.totalPage = (int)Math.Ceiling(page.totalCount * 1.0 / request.PageSize);

            linq = linq.OrderBy(x=>x.ProcurementId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            //var newlinq = map.Map<List<Procurement>>(linq);

            page.data = linq.ToList();

            return Task.FromResult(page);

        }
    }
}